<style lang="scss">
@import "../uv.scss";
</style>
<template>
  <div class="specifications">
    <u-my-layOut :showNavbar="false" :navbarOption="{ bgColor: 'rgba(255,255,255,1)', title: '商品规格' }" :color="{ statusBarHeightColor: '#fff' }">
      <template v-slot:main>
        <div class="h100 p1757575893  oy">
          <div :style="{transform: `translateY(${translateY}px)`}" style="transition: 0.3s;">
            <div class="fz32 pt30 pb30 pl30" style="color: #666666">设置规格</div>
            <uv-form labelWidth="0" labelPosition="left" :model="specsForm" ref="form" :rules="rules">
              <div class="mb20 bfff pl30 pr30 pb30 pt30" v-for="(item, index) in specsForm.specsList" :key="index">
                <div class="pb10 f jcsb aic">
                  <div class="fz32  fw500">{{ item.name }}</div>
                  <button @click="activeIndex = index, $refs.modal.open();" style="color: #D60012!important;" class="common-button m0 p0 fz30">删除</button>
                </div>
                <div class="p1757584012" v-if="item.values && item.values.length">
                  <uv-form-item v-for="(child, childIndex) in item.values" :prop="`specsList.${index}.values.${childIndex}.value`" :key="index + '-' + childIndex" label="">
                    <!-- <uv-form-item v-for="(child, childIndex) in item.values" :key="index + '-' + childIndex" label="" :prop="'specsList.' + index + '.values.' + childIndex + '.value'" :rules="[{type: 'string',required: true,message: '请输入规格值名称',trigger: ['blur', 'change']}]" > -->
                    <div class="w100 p1757573831 mt20 pb10 f aic">
                      <uv-input fontSize="30rpx" color="#333" v-model.trim="child.value" placeholder="输入规格值名称" placeholderStyle="color:#D8D8D8;font-size:30rpx"></uv-input>
                      <div class="pl20">
                        <uv-icon @click="addChildTap(index, childIndex)" v-if="childIndex == (item.values.length - 1)" size="34rpx" color="#9FA0A0" name="plus-circle"></uv-icon>
                        <uv-icon @click="delChildTap(index, childIndex)" v-else size="34rpx" color="#DDDDDD" name="close-circle-fill"></uv-icon>
                      </div>
                    </div>
                  </uv-form-item>
                </div>
              </div>
            </uv-form>
            <div class="bfff pl30 pr30 pb30 pt30 ">
              <div class="pb30">
                <button @click="addSpecsTap" class="p1757570272  common-button f aic jcc  fz34">
                  <uv-icon size="34rpx" color="#333" name="plus"></uv-icon>
                  <div class="pl20 lh1">添加规格类型</div>
                </button>
              </div>
              <button @click="submit" class="p1757569449 common-button ml0 mr0 pt0 pb0">生成SKU列表</button>
            </div>
          </div>
          <u-prices-inventory @translate="translateY = $event" ref="pricesInventoryVue" @submitChange="submitSaveTap"></u-prices-inventory>
        </div>
      </template>
      <template v-slot:footer></template>
    </u-my-layOut>
    <uv-popup ref="skuPopup" mode="center" round="10" :safeAreaInsetBottom="false" :closeOnClickOverlay="false">
      <div class="p1757571029 pt30">
        <div class="p1757573580">
          <uv-input fontSize="30rpx" color="#333" v-model.trim="skuName" placeholder="输入规格值名称" placeholderStyle="color:#D8D8D8;font-size:30rpx"></uv-input>
        </div>
        <div class="mt30" style="border-top: 1rpx solid #eef0f0!important;">
          <button @click="cancalTap" class="common-button pb30 pt30  fz32">取消</button>
          <button @click="submitTap" style="border-left: 2rpx solid #eef0f0!important;color: #D60012!important;" class="  common-button pb30 pt30 fz32">确认</button>
        </div>
      </div>
    </uv-popup>
    <uv-modal ref="modal" title="" showCancelButton content='删除后当前已填写的规格值将不被保留， 确认删除吗？' confirmColor="#D60012" cancelText="暂不删除" confirmText="确认删除" @cancel="cancelDelTap" @confirm="delTap"></uv-modal>
  </div>
</template>

<script>

import myLayOutVue from '../components/layOut.vue'
import pricesInventoryVue from '../components/pricesInventory.vue'

import { generateAllSkus, getSpecValues } from "@/api/merchant.js";
import pageMixin from "../mixin/page.js";
export default {
  components: {
    'u-my-layOut': myLayOutVue,
    'u-prices-inventory': pricesInventoryVue,
  },
  mixins: [pageMixin],
  data() {
    return {
      translateY: 0,
      activeIndex: null,
      skuName: '',
      specsForm: {
        specsList: [],
      },
      copySpecsForm: {},
      tableData: [],
      statusBarHeight: 0,
      rules: {}
    }
  },
  onReady() {
    setTimeout(() => {
      this.initPage()
    }, 500);
  },
  methods: {
    initPage() {
      uni.getStorage({
        key: 'storageForm', success: res => {
          if (res.data) {
            let { id, sku_object } = JSON.parse(res.data)
            if (!id) return
            if (sku_object.specs && sku_object.specs.length) {
              this.$set(this.specsForm, 'specsList', sku_object.specs)
              this.$set(this.copySpecsForm, 'specsList', sku_object.specs)
              this._initRules()
            }
            if (sku_object._skus && sku_object._skus.length) {
              this.$refs.pricesInventoryVue.initPage(sku_object._skus)
            }
          } else {
            this._initRules()
          }
        }
      });

    },
    submitSaveTap(value) {
      let sku_object = {
        specs: this.copySpecsForm.specsList,
        _skus: value._skus,
        skus: value.skus,
      }
      uni.getStorage({
        key: 'storageForm', success: res => {
          if (res.data) {
            let launchForm = JSON.parse(res.data)
            launchForm.sku_object = sku_object
            launchForm._sku_object = `共${value.skus.length}个规格`
            uni.setStorage({ key: 'storageForm', data: JSON.stringify(launchForm) });
            uni.navigateBack({ delta: 1 });
          }
        }
      });
    },
    addSpecsTap() {
      if (this.specsForm.specsList.length == 2) return uni.$uv.toast('最多添加两个规格值类型 请删除后重新添加')
      this.$refs.skuPopup.open()

    },
    addChildTap(index) {
      this.specsForm.specsList[index].values.push({ value: '' })
      this._initRules()
    },
    delChildTap(index, childIndex) {
      this.specsForm.specsList[index].values.splice(childIndex, 1)
      this._initRules()
    },
    cancelDelTap() {
      this.$refs.modal.close();
      this.activeIndex = null
    },
    delTap() {
      if (this.activeIndex > -1) this.specsForm.specsList.splice(this.activeIndex, 1)
      this.$refs.modal.close();
      this.activeIndex = null
      this._initRules()
    },
    cancalTap() {
      this.$refs.skuPopup.close()
      this.skuName = null
    },
    submitTap() {
      if (!this.skuName) return uni.$uv.toast('请输入规格类型')
      this.specsForm.specsList.push({ name: this.skuName, values: [{ value: '' }] })
      this.cancalTap()
    },
    _initRules() {
      let rules = {}
      this.specsForm.specsList.forEach((i, iI) => {
        i.values.forEach((c, cI) => {
          rules[`specsList.${iI}.values.${cI}.value`] = { type: 'string', required: true, message: '请输入规格值名称', trigger: ['blur', 'change'] }
        })
      })
      this.rules = rules
    },
    submit() {
      if (!this.specsForm.specsList.length) return uni.$uv.toast('请添加规格类型')
      this._initRules()
      this.$refs.form.validate().then(res => {
        uni.showLoading({ title: '生成中', mask: true })
        generateAllSkus({ specs: this.specsForm.specsList }).then(res => {
          if (res.code === 200) {
            uni.hideLoading()
            this.copySpecsForm = JSON.parse(JSON.stringify(this.specsForm))
            uni.$uv.toast('生成成功')

            this.$refs.pricesInventoryVue.initPage(this._skus(res.result))
          }
        })
      }).catch(errors => {
      })
    },
    removeTrailingZeros(str) {
      if(this.isEmpty(str)) {
        return ''
      }
      return  String(str).replace(/(\.\d*?[1-9])0+$|\.0+$/, '$1');
    },
    _skus(data) {
      let specsList = []
      Object.entries(data).forEach(([key, value], ci) => {
        console.log(value)
        value.forEach((item, index) => {
          item.id = item.id || 0
          item.name = item.spec_values.join(',')
          item.weight = this.removeTrailingZeros(item.weight) || null
          item.price = this.removeTrailingZeros(item.price) || null
          item.stock = this.removeTrailingZeros(item.stock) || null
          item.market_price = this.removeTrailingZeros(item.market_price) || null
          item.image = item.image
          if (Array.isArray(item.image)) {
            item._image = item.image
          } else {
            item._image = item.image && [{ url: item.image }] || []
          }
        })
        specsList.push({ name: key, values: value })
      });
      return specsList

    },
    hideKeyboard() {
      uni.hideKeyboard()
    },


  }
}
</script>
<style>
page {
  color: #333;  background-color: #F7F8F8;
  
}
</style>
<style lang="scss" scoped>
@import "../common.scss";

.p1757570272 {
  height: 80rpx !important;
  line-height: 80rpx !important;
  font-size: 34rpx !important;
  color: #333333 !important;
  background: #fff !important;
  border: 2rpx solid #9fa0a0 !important;
  border-radius: 8rpx !important;
}
.p1757569449 {
  height: 90rpx;
  background: #de0012 !important;
  font-weight: 500;
  font-size: 36rpx !important;
  color: #ffffff !important;
  border-radius: 8rpx !important;
  width: 100%;
}
.p1757571029 {
  width: 85vw;
  .common-button {
    width: 50% !important;
    border-top: none !important;
    border-left: none !important;
    border-right: none !important;
  }
}
.p1757573580 {
  padding: 30rpx 60rpx;
}
</style>

